package com.zheng.api.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.zheng.api.server.service.ApiServerPayService;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Description: 接收处理微信通知
 * @author lvb
 * @date 2017-07-05
 * @version V1.0
 * @Copyright:
 */
@Controller
@Api(value = "微信支付回调通知控制器", description = "微信支付回调通知控制器")
@RequestMapping("/v1/pay")
public class ApiPayNotify4WxController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ApiPayNotify4WxController.class);

	@Autowired
	private ApiServerPayService apiServerPayService;
	@Autowired
	UpmsSystemParamService upmsSystemParamService;

	/**
	 * 微信支付(统一下单接口)后台通知响应
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
     */
	@RequestMapping("/notify/wxPayNotifyRes.htm")
	@ApiOperation(value = "微信支付回调通知")
	@ResponseBody
	public String wxPayNotifyRes(HttpServletRequest request) throws ServletException, IOException {
		LOGGER.info("====== 开始接收微信支付回调通知 ======");
		String notifyRes = doWxPayRes(request);
		LOGGER.info("响应给微信:{}", notifyRes);
		LOGGER.info("====== 完成接收微信支付回调通知 ======");
		return notifyRes;
	}

	private String doWxPayRes(HttpServletRequest request) throws ServletException, IOException {
		String logPrefix = "【微信支付回调通知】";
		String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
		LOGGER.info("{}通知请求数据:reqStr={}", logPrefix, xmlResult);
		String isForward = upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_PAYORDER_TEST_FORWARD_ENABLE");
		if("true".equals(isForward)){
			String orderprefix = upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_PAYORDER_TEST_FORWARD_PREFIX");
			WxPayOrderNotifyResult result = WxPayOrderNotifyResult.fromXML(xmlResult);
			String out_trade_no = result.getOutTradeNo();			// 商户系统订单号
			if(out_trade_no!=null && orderprefix!=null && out_trade_no.startsWith(orderprefix)){
				String forward_address = upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_PAYORDER_TEST_FORWARD_WXNOTIFYDDRESS");
				HttpPost httpPost = null;
				try {
					HttpClient httpClient = new DefaultHttpClient();
					httpPost = new HttpPost(forward_address);
					httpPost.setHeader("Content-type", "application/xml; charset=utf-8");
					HttpEntity httpEntity = new StringEntity(xmlResult, "utf-8");
					httpPost.setEntity(httpEntity);
					HttpResponse httpResponse = httpClient.execute(httpPost);
					int statusCode = httpResponse.getStatusLine().getStatusCode();
					if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
						HttpEntity resEntity = httpResponse.getEntity();
						if (resEntity != null) {
							String ret = EntityUtils.toString(resEntity, Charset.forName("utf-8"));
							return ret;
						}
					}
				} catch (Exception e) {
					LOGGER.error("转发测试环境异常",e);
				} finally {
					if (httpPost != null) {
						httpPost.releaseConnection();
					}
				}
				return null;
			}else{
				return apiServerPayService.doWxPayNotify(xmlResult);
			}
		}
		return apiServerPayService.doWxPayNotify(xmlResult);
	}

}
